#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Author:  LJ
Email:   admin@attacker.club
Time:    2020/4/10 16:38
Description: 
"""

import os
import oss2
from itertools import islice
import datetime
import hashlib
import time
import os
import sys


def print_run_time(func):
    def wrapper(*args, **kw):
        local_time = time.time()
        func(*args, **kw)
        print('[+] [%s] Run time is %.2f' %
              (func.__name__, time.time() - local_time))
    return wrapper


today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)
backuptime = yesterday.strftime('%Y-%m-%d')

# 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
auth = oss2.Auth('LTAI4FteGCWYNVPas61vx5sJ', 'bUqjfENA2RVu1U7U61JMzl278hDP5T')
# Endpoint以杭州为例，其它Region请按实际情况填写。
bucket = oss2.Bucket(
    auth, 'http://oss-cn-hangzhou.aliyuncs.com', 'xdrds-backup')


def display():
    # oss2.ObjectIteratorr用于遍历文件。
    print("目录列表:")
    for b in islice(oss2.ObjectIterator(bucket), 10):
        print(b.key)


# 下载文件
def download(file):

    s = bucket.get_object_to_file(file, file)
    if s.status == 200:
        print("[+]下载成功")
    else:
        print("[-]下载失败! %d" % s.status)
        # bucket.delete_object('<yourObjectName>')


# 上传文件
@print_run_time
def upload(filename, srcfile):
    s = bucket.put_object_from_file(filename, srcfile)
    if s.status == 200:
        print("""[+] "%s" 上传成功 """ % srcfile)
    else:
        print("""[+] "%s" 上传失败! %d""" % (srcfile, s.status))


# 断点续传
@print_run_time
def breakpoint_continuingly(filename, srcfile):
    oss2.resumable_upload(bucket, filename, srcfile)
    print("""[+] "%s" 上传成功 """ % srcfile)


# 执行命令
@print_run_time
def cmdrun(command):
    os.system(command)


@print_run_time
def FileMd5(filename):
    if not os.path.isfile(filename):
        print("""[-] "%s" 文件不存在!""" % filename)
        sys.exit(1)
    res = hashlib.md5(open(filename, 'rb').read()).hexdigest()

    print("""[+] '%s' 生成MD5:%s""" % (filename, res))
    md5file = "%s.md5" % filename
    with open(md5file, 'w') as f:
        f.write(res)


if __name__ == '__main__':

    starttime = "2020-03-10 16:42:00"
    endtime = "2020-04-10 16:42:00"

    BackupFile = "/data/rds_backup/recognize_log.%s.sql" % backuptime
    Backupname = "recognize_log.%s.sql" % backuptime

    backupcmd = """mysqldump  -udevelop -pXidian123456  -h172.16.160.61 recognize_core_00 recognize_log_all -w "gmt_create >='%s' and  gmt_create <='%s' " > %s """ % (
        starttime, endtime, BackupFile)  # 备份数据
    deletecmd = """mysql  -uroot -p123456 -h127.0.0.1 -e  " DELETE FROM recognize_core_00.recognize_log_all  WHERE gmt_create >='%s' and  gmt_create <='%s'" """ % (
        starttime, endtime)  # 删除数据

    print("数据库文件: %s" % BackupFile)
    showcmd = cmd.replace('Xidian123456', '******')
    print("sql: %s" % showcmd)

    res = cmdrun(backupcmd)  # 执行脚本
    if res == 0:
        print("[+]recognize_log_all表 备份成功")
        res = os.system(deletecmd)
        print("[+]recognize_log_all表 数据删除")
    else:
        print("[-]备份失败")
        sys.exit(1)

    FileMd5(BackupFile)  # 生成md5
    filemd5 = '%s.md5' % Backupname
    filedir = '%s.md5' % BackupFile
    upload(filemd5, filedir)  # 上传MD5
    breakpoint_continuingly(Backupname, BackupFile)  # 断点续传
    display()
